package com.wanxi.product.service;

import com.wanxi.product.core_sevice.SkuService;
import com.wanxi.product.service.api.dto.*;
import com.wanxi.product.service.api.result.CommonResult;
import com.wanxi.product.core_sevice.SpuService;
import com.wanxi.product.service.api.entity.SpuTag;
import com.wanxi.product.service.api.feign.ProductEnterpriseService;
import com.wanxi.product.service.api.query.admin.TypeQuery;
import com.wanxi.product.service.api.util.TypeEnum;
import com.wanxi.product.service.api.vo.enterprise.TypeAddInVo;
import com.wanxi.product.service.api.vo.enterprise.TypeFindAllOutVo;
import com.wanxi.product.service.api.vo.enterprise.TypeUpdateInVo;
import com.wanxi.product.service.api.vo.enterprise.*;
import com.wanxi.product.service.api.query.enterprise.*;
import com.wanxi.product.util.BeanCopyUtils;
import com.wanxi.product.util.Check;
import com.wanxi.product.util.VoToDto;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "商家接口")
@RequestMapping("/enterprise")
@RestController
public class ProductEnterpriseServiceImpl implements ProductEnterpriseService {
    @Resource
    private SpuService spuService;

    @Resource
    private SkuService skuService;

    @Resource
    private Check check;

    @Override
    @ApiOperation("添加sku")
    @PostMapping("/sku/add")
    public CommonResult<Long> addSku(SkuAddInVo skuAddInVo) {
        SkuDto skuDto = VoToDto.skuVTD(skuAddInVo);
        Long skuId = skuService.addSku(skuDto);

        /*价格表新增数据*/
        PriceDto priceDto = PriceDto.builder()
                .skuId(skuId)
                .build();
        skuService.addPrice(priceDto);
        return CommonResult.success(skuId);
    }

    @Override
    @ApiOperation("获取sku列表")
    @GetMapping("/sku/findAll")
    public CommonResult<List<SkuFindAllOutVo>> findAllSku(SkuQuery skuQuery) {
        List<SkuFindAllOutVo> skuFindAllOutVoList = new ArrayList<>();
        List<SkuDto> skuDtoList = new ArrayList<>();

        /*根据sku id、名称、市场价区间查找*/
        if (skuQuery.getSkuId() != null
                || skuQuery.getSkuName() != null
                || skuQuery.getPriceUpper() != null
                || skuQuery.getPriceLower() != null) {
            SkuQueryDto skuQueryDto = SkuQueryDto.builder()
                    .skuId(skuQuery.getSkuId())
                    .skuName(skuQuery.getSkuName())
                    .priceUpper(skuQuery.getPriceUpper())
                    .priceLower(skuQuery.getPriceLower())
                    .build();
            List<SkuDto> skuList = skuService.findAllSku(skuQueryDto);
            for (SkuDto skuDto : skuList) {
                skuDtoList.add(skuDto);
            }
        }

        /*根据type id找到spu，根据spu找到下面的sku*/
        if (skuQuery.getTypeId() != null) {
            SpuQuery spuQuery = SpuQuery.builder()
                    .typeId(skuQuery.getTypeId())
                    .build();
            List<SpuDto> spuDtoList = spuService.findAllSpu(spuQuery);
            for (SpuDto spuDto : spuDtoList) {
                SkuQueryDto skuQueryDto1 = SkuQueryDto.builder()
                        .spuId(spuDto.getSpuId())
                        .build();
                List<SkuDto> skuDtoList1 = skuService.findAllSku(skuQueryDto1);
                for (SkuDto skuDto : skuDtoList1) {
                    skuDtoList.add(skuDto);
                }
            }
        }

        /*封装数据*/
        for (SkuDto skuDto : skuDtoList) {
            SkuFindAllOutVo skuFindAllOutVo = SkuFindAllOutVo.builder()
                    .skuId(skuDto.getSkuId())
                    .skuName(skuDto.getSkuName())
                    .img(skuDto.getImg())
                    .marketPrice(skuDto.getMarketPrice())
                    .build();
            skuFindAllOutVoList.add(skuFindAllOutVo);
        }
        return CommonResult.success(skuFindAllOutVoList);
    }

    @Override
    @ApiOperation("根据id查找sku")
    @ApiImplicitParam(name = "id", value = "要查询的商品sku的id", dataType = "Long")
    @GetMapping("/sku/findById")
    public CommonResult<SkuFindByIdOutVo> findSkuById(Long skuId) {
        /*名称，图片，市场价，商品规格，商品描述*/
        SkuDto skuDto = skuService.findSkuBySkuId(skuId);
        SkuFindByIdOutVo skuFindByIdOutVo = SkuFindByIdOutVo.builder()
                .skuName(skuDto.getSkuName())
                .img(skuDto.getImg())
                .marketPrice(skuDto.getMarketPrice())
                .specifications(skuDto.getSpecifications())
                .description(skuDto.getDescription())
                .build();

        /*分类名称*/
        SpuDto spuDto = spuService.findSpuBySpuId(skuDto.getSpuId());
        TypeDto typeDto = spuService.findTypeByTypeId(spuDto.getTypeId());
        skuFindByIdOutVo.setTypeName(typeDto.getTypeName());

        return CommonResult.success(skuFindByIdOutVo);
    }

    @Override
    @ApiOperation("修改sku")
    @PutMapping("/sku/update")
    public CommonResult updateSku(SkuUpdateInVo skuUpdateInVo) {
        /*检查此sku是否在商家管理下*/
        if (!check.checkEnterpriseSku(skuUpdateInVo.getSkuId(), skuUpdateInVo.getEnterpriseId())) {
            return CommonResult.failed("商家无权管理此sku！");
        }
        /*更新名称，图片路径，描述，规格，市场价*/
        SkuDto skuDto = VoToDto.skuVTD(skuUpdateInVo);
        Long skuId = skuService.updateSku(skuDto);

        return CommonResult.success(skuId);
    }

    @Override
    @ApiOperation("删除sku")
    @ApiImplicitParam(name = "id", value = "要删除sku的id", dataType = "Long")
    @PutMapping("/sku/delete")
    public CommonResult deleteSkuById(Long skuId) {
        skuService.deleteSku(skuId);
        skuService.deletePrice(skuId);

        return CommonResult.success();
    }

    @Override
    @ApiOperation("添加spu")
    @PostMapping("/spu/add")
    public CommonResult<Long> addSpu(SpuAddInVo spuAddInVo) {
        /*添加标签外其他属性*/
        SpuDto spuDto = VoToDto.spuVTD(spuAddInVo);
        Long spuId = spuService.addSpu(spuDto);

        /*添加商品标签*/
        if (!spuAddInVo.getTagId().isEmpty()) {
            SpuTagDto spuAddTagDto = new SpuTagDto();
            spuAddTagDto.setSpuId(spuId);
            for (Long tagId : spuAddInVo.getTagId()) {
                spuAddTagDto.setTagId(tagId);
                spuService.addSpuTag(spuAddTagDto);
            }
        }

        return CommonResult.success(spuId);
    }

    @Override
    @ApiOperation("查找当前商家管理所有的SPU")
    @GetMapping("/spu/findAll")
    public CommonResult<List<SpuFindAllOutVo>> findAllSpu(SpuQuery spuQuery) {
        List<SpuDto> spuFindAllOutDtoList = spuService.findAllSpu(spuQuery);
        List<SpuFindAllOutVo> spuFindAllOutVoList = new ArrayList<>();

        for (SpuDto spuFindAllOutDto : spuFindAllOutDtoList) {
            /*通过id查找分类名称*/
            TypeDto typeFindByIdOutDto = spuService.findTypeByTypeId(spuFindAllOutDto.getTypeId());

            /*封装数据*/
            SpuFindAllOutVo spuFindAllOutVo = SpuFindAllOutVo.builder()
                    .typeName(typeFindByIdOutDto.getTypeName())
                    .spuId(spuFindAllOutDto.getSpuId())
                    .spuName(spuFindAllOutDto.getSpuName())
                    .spuImg(spuFindAllOutDto.getImg())
                    .description(spuFindAllOutDto.getContent())
                    .state(spuFindAllOutDto.getState())
                    .build();
            spuFindAllOutVoList.add(spuFindAllOutVo);
        }

        return CommonResult.success(spuFindAllOutVoList);
    }

    @Override
    @ApiOperation("根据id查询当前商家下SPU信息")
    @GetMapping("/spu/findById")
    public CommonResult<SpuFindByIdOutVo> findSpuById(SpuFindByIdInVo spuFindByIdInVo) {
        /*查找该SPU是否在该商家管理下*/
        SpuDto spuDto = spuService.findSpuBySpuId(spuFindByIdInVo.getSpuId());

        if (!spuDto.getEnterpriseId().equals(spuFindByIdInVo.getEnterpriseId())) {
            return CommonResult.failed("该商家无权对此SPU进行操作");
        }

        /*根据SPU id查找对应标签id*/
        SpuTagQuery spuTagQuery = SpuTagQuery.builder()
                .spuId(spuDto.getSpuId())
                .build();
        List<SpuTag> tagIdList = spuService.findAllSpuTag(spuTagQuery);

        /*通过标签id查找标签名称*/
        List<String> tagNameList = new ArrayList<>();
        for (SpuTag spuTag : tagIdList) {
            tagNameList.add(spuService.findTagByTagId(spuTag.getTagId()).getTagName());
        }

        /*根据分类id查找分类名称*/
        TypeDto typeFindByIdOutDto = spuService.findTypeByTypeId(spuDto.getTypeId());
        String typeName = typeFindByIdOutDto.getTypeName();

        /*封装数据*/
        SpuFindByIdOutVo outVo = SpuFindByIdOutVo.builder()
                .spuName(spuDto.getSpuName())
                .spuImg(spuDto.getImg())
                .typeName(typeName)
                .tagName(tagNameList)
                .description(spuDto.getContent())
                .state(spuDto.getState())
                .build();

        return CommonResult.success(outVo);
    }

    @Override
    @ApiOperation("修改spu")
    @PutMapping("/spu/update")
    public CommonResult updateSpu(SpuUpdateInVo spuUpdateInVo) {
        /*查找该SPU是否在该商家管理下*/
        if (!check.checkEnterpriseSpu(spuUpdateInVo.getSpuId(), spuUpdateInVo.getEnterpriseId())) {
            return CommonResult.failed("该商家无权对此SPU进行操作");
        }

        /*检查分类id是否有对应字段*/
        try {
            spuService.findTypeByTypeId(spuUpdateInVo.getTypeId());
        } catch (Exception e) {
            return CommonResult.failed("分类不存在！");
        }

        /*修改除标签外SPU属性*/
        SpuDto spuDto = VoToDto.spuVTD(spuUpdateInVo);
        spuService.updateSpu(spuDto);

        /*修改商品标签*/
        if (!spuUpdateInVo.getTagId().isEmpty()) {
            List<Long> tagIdList = spuUpdateInVo.getTagId();
            /*根据spu id删除*/
            spuService.deleteBySpuId(spuUpdateInVo.getSpuId());

            /*添加新标签*/
            for (Long addTagId : tagIdList) {
                SpuTagDto spuTagAddInDto = new SpuTagDto();
                spuTagAddInDto.setSpuId(spuUpdateInVo.getSpuId());
                spuTagAddInDto.setTagId(addTagId);
                spuService.addSpuTag(spuTagAddInDto);
            }
        }

        return CommonResult.success();
    }

    @Override
    @ApiOperation("删除spu")
    @PutMapping("/spu/delete")
    public CommonResult deleteSpu(SpuDeleteInVo spuDeleteInVo) {
        Assert.notNull(spuDeleteInVo.getSpuId(), "spu id不能为空");
        Assert.notNull(spuDeleteInVo.getEnterpriseId(), "商家id不能为空");

        if (!check.checkEnterpriseSpu(spuDeleteInVo.getSpuId(), spuDeleteInVo.getEnterpriseId())) {
            return CommonResult.failed("该商家无权对此SPU进行操作");
        }

        int i1 = spuService.deleteSpu(spuDeleteInVo.getSpuId());
        int i2 = spuService.deleteBySpuId(spuDeleteInVo.getSpuId());

        if (i1 == 1 && i2 == 1) {
            return CommonResult.success();
        } else
            return CommonResult.failed();
    }

    @Override
    @ApiOperation("添加分类")
    @PostMapping("/type/add")
    public CommonResult<Long> addType(TypeAddInVo typeAddInVo) {
        if (check.checkTypeLevel(typeAddInVo.getParentId()).equals(TypeEnum.二级分类)) {
            TypeDto typeAddInDto = BeanCopyUtils.copy(typeAddInVo, TypeDto.class);
            return CommonResult.success(spuService.addType(typeAddInDto));
        }
        return CommonResult.failed("无法添加三级分类以外的分类");
    }

    @Override
    @ApiOperation("获取分类列表")
    @GetMapping("/type/findAll")
    public CommonResult<List<TypeFindAllOutVo>> findAllType(TypeQuery typeQuery) {
        List<TypeFindAllOutVo> typeVoList = new ArrayList<>();

        List<TypeDto> typeDtoList = spuService.findAllType(typeQuery);
        for (TypeDto typeDto : typeDtoList) {
            if (check.checkTypeLevel(typeDto.getTypeId()).equals(TypeEnum.三级分类)) {
                TypeFindAllOutVo typeVo = TypeFindAllOutVo.builder()
                        .typeId(typeDto.getTypeId())
                        .typeName(typeDto.getTypeName())
                        .img(typeDto.getImg())
                        .description(typeDto.getDescription())
                        .state(typeDto.getState())
                        .build();
                TypeDto secondParentDto = spuService.findTypeByTypeId(typeDto.getParentId());
                TypeDto firstParentDto = spuService.findTypeByTypeId(secondParentDto.getParentId());
                typeVo.setFirstParentTypeName(firstParentDto.getTypeName());
                typeVo.setSecondParentTypeName(secondParentDto.getTypeName());
                typeVoList.add(typeVo);
            }
        }
        return CommonResult.success(typeVoList);
    }

    @Override
    @ApiOperation("根据id查询分类")
    @ApiImplicitParam(name = "typeId", value = "要查找分类的id", dataType = "Long")
    @GetMapping("/type/findById")
    public CommonResult<TypeFindByIdOutVo> findTypeById(Long typeId) {
        TypeDto typeFindByIdOutDto = spuService.findTypeByTypeId(typeId);

        if (check.checkTypeLevel(typeId).equals(TypeEnum.三级分类)) {
            TypeFindByIdOutVo typeFindByIdOutVo = TypeFindByIdOutVo.builder()
                    .typeName(typeFindByIdOutDto.getTypeName())
                    .img(typeFindByIdOutDto.getImg())
                    .description(typeFindByIdOutDto.getDescription())
                    .state(typeFindByIdOutDto.getState())
                    .build();
            TypeDto typeSecondParentDto = spuService.findTypeByTypeId(typeFindByIdOutDto.getParentId());
            TypeDto typeFirstParentDto = spuService.findTypeByTypeId(typeSecondParentDto.getParentId());
            typeFindByIdOutVo.setSecondParentTypeName(typeSecondParentDto.getTypeName());
            typeFindByIdOutVo.setFirstParentTypeName(typeFirstParentDto.getTypeName());
            return CommonResult.success(typeFindByIdOutVo);
        }
        return CommonResult.failed("此分类不是商家管理的三级分类！");
    }

    @Override
    @ApiOperation("修改分类")
    @PutMapping("/type/update")
    public CommonResult updateType(TypeUpdateInVo typeUpdateInVo) {
        if (check.checkTypeLevel(typeUpdateInVo.getTypeId()).equals(TypeEnum.三级分类)) {
            TypeDto typeDto = BeanCopyUtils.copy(typeUpdateInVo, TypeDto.class);
            return CommonResult.success(spuService.updateType(typeDto));
        }
        return CommonResult.failed("此分类无权管理");
    }

    @Override
    @ApiOperation("删除分类")
    @ApiImplicitParam(name = "id", value = "要删除分类的id", dataType = "Long")
    @PutMapping("/type/delete")
    public CommonResult deleteTypeById(Long typeId) {
        if (check.checkTypeLevel(typeId).equals(TypeEnum.三级分类)) {
            spuService.deleteType(typeId);
            return CommonResult.success();
        }
        return CommonResult.failed("此分类无权管理");
    }
}
